package sftp

import (
	"io"
	"os"
	"path"

	"github.com/conduitio/bwlimit"
)

// RemoteDir 远程目录，默认配置
func (c *Client) RemoteDir(remoteDir string) ([]os.FileInfo, error) {
	return c.RemoteDirWithConf(c.defaultConf, remoteDir)
}

// RemoteDirWithConf 远程目录，自定义配置
func (c *Client) RemoteDirWithConf(conf *Conf, remoteDir string) ([]os.FileInfo, error) {
	var (
		err      error
		sftpConn *Conn
	)

	// 连接sftp
	sftpConn, err = c.ConnectWithConf(conf)
	if err != nil {
		return nil, err
	}
	defer sftpConn.Close()

	fList, err := sftpConn.ReadDir(remoteDir)
	if err != nil {
		return nil, err
	}

	return fList, nil
}

// DownloadFile 下载文件，默认sftp配置，不限速
func (c *Client) DownloadFile(localPath, remoteFile string) error {
	return c.DownloadFileWithConf(c.defaultConf, localPath, remoteFile)
}

// DownloadFileWithConf 下载文件，自定义sftp配置，不限速
func (c *Client) DownloadFileWithConf(conf *Conf, localPath, remoteFile string) error {
	return c.DownloadFileLimitWithConf(conf, localPath, remoteFile, 0)
}

// DownloadFileLimit 下载文件，默认sftp配置，限速
func (c *Client) DownloadFileLimit(localPath, remoteFile string, rate int) error {
	return c.DownloadFileLimitWithConf(c.defaultConf, localPath, remoteFile, rate)
}

// DownloadFileLimitWithConf 下载文件，自定义sftp配置，限速
func (c *Client) DownloadFileLimitWithConf(conf *Conf, localPath, remoteFile string, rate int) error {
	fileName := path.Base(remoteFile)
	writer, err := os.Create(path.Join(localPath, fileName))
	if err != nil {
		return err
	}
	defer writer.Close()

	conn, err := c.ConnectWithConf(conf)
	if err != nil {
		return err
	}
	defer conn.Close()
	// 返回远程读文件
	reader, err := conn.DownloadReaderLimit(remoteFile, rate)
	if err != nil {
		return err
	}
	defer reader.Close()

	_, err = io.Copy(writer, reader)
	if err != nil {
		return err
	}
	return nil
}

// DownloadReaderLimit 下载文件，限速
func (c *Conn) DownloadReaderLimit(remoteFile string, rate int) (io.ReadCloser, error) {
	var err error

	// 打开远程文件
	dstFile, err := c.Open(remoteFile)
	if err != nil {
		return nil, err
	}
	c.fp = dstFile

	// 限速 KB
	readLimit := bwlimit.Byte(rate) * bwlimit.KB
	// 下载读限速
	downloadReader := bwlimit.NewReader(dstFile, readLimit)
	return downloadReader, nil
}

// DownloadStreamLimitWithConfV1 下载文件，自定义sftp配置，限速
// 返回Reader需手工关闭
func (c *Client) DownloadStreamLimitWithConfV1(conf *Conf, remoteFile string, rate int) (io.Reader, error) {
	var (
		err      error
		sftpConn *Conn
	)

	// 连接sftp
	sftpConn, err = c.ConnectWithConf(conf)
	if err != nil {
		return nil, err
	}
	defer sftpConn.Close()

	dstFile, err := sftpConn.Open(remoteFile)
	if err != nil {
		return nil, err
	}
	defer dstFile.Close()
	// 限速 KB
	readLimit := bwlimit.Byte(rate) * bwlimit.KB

	// 下载读限速
	downloadReader := bwlimit.NewReader(dstFile, readLimit)

	return downloadReader, nil
}
